<?php
/**
 * Created by PhpStorm.
 * User: 764432054@qq.com
 * Date: 2020/5/21
 * Time: 21:52
 */
$ip = "0.0.0.0";
$port = $argv[1];
$sockefd = socket_create(AF_INET,SOCK_STREAM,0);
socket_set_option($sockefd,SOL_SOCKET,SO_REUSEPORT,1);
socket_bind($sockefd,$ip,$port);
socket_listen($sockefd,5);
echo "Server listen on {$ip}:$port".PHP_EOL;

while (1){

    $connfd = socket_accept($sockefd);
    $message = "php is the best language in the world!";
    $remoteIp;
    $remoteAddr;
    //获取socket 文件描述符绑定的端口和地址
    //网卡接收数据时执行的中断函数会根据端口找到对应的文件描符并写入其缓冲区
    //一般带有缓冲的称为IO流【用户空间】
    socket_getpeername($connfd,$remoteIp,$remoteAddr);
    echo "有客户端连接，ip为：".$remoteIp.",端口为：".$remoteAddr.PHP_EOL;

    if ($connfd){
        socket_send($connfd,$message,strlen($message),0);
        while (1){
            $recvMessage = "";
            $recvBytes = socket_recv($connfd,$recvMessage,8192,0);
            if ($recvBytes){
                $sendBytes = socket_sendto($connfd,$recvMessage,$recvBytes,0,$remoteIp,$remoteAddr);
                fprintf(STDOUT,"发送了%d 字节,recvMessage=%s\n",$sendBytes,$recvMessage);
            }
        }
    }

}

socket_close($sockefd);
socket_close($connfd);